'use strict';

const BaseController = require('../base');
const {literal} = require("sequelize");
class OrderController extends BaseController {
  static get serviceName() {
    return 'business.order';
  }
  formatOrder(sort) {
    return [
      literal(`
        CASE \`Order\`.status
          WHEN 'pending' THEN 1
          WHEN 'pending_pricing' THEN 2
          WHEN 'refunding' THEN 3
          WHEN 'shipped' THEN 4
          WHEN 'paid' THEN 5
          WHEN 'completed' THEN 6
          WHEN 'refunded' THEN 7
          WHEN 'cancelled' THEN 8
          ELSE 9
        END
      `),
      ['create_time', 'desc'],
    ]
  }

  /**
   * 获取订单详情
   */
  async detail() {
    const { ctx } = this;
    const { id } = ctx.query;
    try {
      const result = await this.service.detail({ id });
      ctx.success(result);
    } catch (error) {
      ctx.error(400, error.message);
    }
  }

  /**
   * 取消订单
   */
  async cancel() {
    const { ctx } = this;
    const { id } = ctx.request.body;
    try {
      await this.service.cancel({ id });
      ctx.success();
    } catch (error) {
      ctx.error(400, error.message);
    }
  }

  /**
   * 设置订单价格
   */
  async setPrice() {
    const { ctx } = this;
    const { order_id, store_id, amount } = ctx.request.body;
    try {
      await this.service.setPrice({ order_id, store_id, amount });
      ctx.success();
    } catch (error) {
      ctx.error(400, error.message);
    }
  }

  /**
   * 申请退款
   */
  async refund() {
    const { ctx } = this;
    const { id, refund_reason, is_admin } = ctx.request.body;
    try {
      await this.service.refund({
        id,
        refund_reason,
        is_admin
      });
      ctx.success();
    } catch (error) {
      ctx.error(400, error.message);
    }
  }

  /**
   * 处理退款
   */
  async refundConfirm() {
    const { ctx } = this;
    try {
      await this.service.refundConfirm(ctx.request.body);
      ctx.success();
    } catch (error) {
      ctx.error(400, error.message);
    }
  }

  /**
   * 确认行程
   */
  async confirm() {
    const { ctx } = this;
    const { id, confirm_remark } = ctx.request.body;
    try {
      await this.service.confirm({ id, confirm_remark });
      ctx.success();
    } catch (error) {
      ctx.error(400, error.message);
    }
  }

  /**
    * 完成行程
   */
  async complete() {
    const { ctx } = this;
    const { id, complete_remark } = ctx.request.body;
    try {
      await this.service.complete({ id, complete_remark });
      ctx.success();
    } catch (error) {
      ctx.error(400, error.message);
    }
  }
  /**
   * 删除订单
   */
  async delete() {
    const { ctx } = this;
    const { id } = ctx.request.body;
    try {
      await this.service.delete({ id });
      ctx.success();
    } catch (error) {
      ctx.error(400, error.message);
    }
  }
}

module.exports = OrderController;
